/**============================================================================
 Confidential Information - Limited distribution to authorized persons only.
 This software is protected as an unpublished work under the U.S. Copyright
 Act of 1976.

 Copyright (c) 2012, BluePhoenix Solutions, Inc. All rights reserved.
 ----------------------------------------------------------------------------
 file......: Downloader.java
 Author....: Vyacheslav Kovalyov
 Created...: 1/18/12

 Description:

 ============================================================================*/
package com.bphx.android.network;

import android.content.Context;
import android.os.AsyncTask;
import com.bphx.android.BaseAsynchResult;
import com.bphx.android.IAsynchResult;
import com.bphx.android.activities.DownloadStatusActivity;
import com.bphx.android.db.Storage;
import com.bphx.android.exception.BaseException;
import com.bphx.android.words.Word;

import java.util.List;

import static com.bphx.android.network.ManagerStatus.*;
import static com.bphx.android.utils.ChangeStatusProxy.getInstance;

/**
 * @author Vyacheslav Kovalyov
 * @version 1.0
 */
public class Downloader extends AsyncTask<String, String, IAsynchResult> {

    public Downloader(Context context) {
        this.context = context;
    }

    @Override
    protected IAsynchResult doInBackground(String... params) {

        NetworkManager manager = new NetworkManager(params[0], params[1], context);

        try {

            publishStatus(DOWNLOAD_STARTED);
            List<Word> words = manager.loadWords();
            publishStatus(DOWNLOAD_FINISHED);
            publishStatus(MERGE_STARTED);
            manager.mergeWithLocal(new Storage(context), words);
            publishStatus(MERGE_FINISHED);
        } catch (BaseException e) {

            return new BaseAsynchResult(e.getMessage());
        }

        return new BaseAsynchResult();
    }

    private void publishStatus(ManagerStatus status, String... values) {
        currentStatus = status;
        publishProgress(values);
    }

    @Override
    protected void onProgressUpdate(String... values) {
        getInstance().changeStatusFor(DownloadStatusActivity.class.getName(), currentStatus, values);
    }

    @Override
    protected void onPostExecute(IAsynchResult asynchResult) {
        if (asynchResult.isSuccess()) {
            publishStatus(SUCCESS);
        } else {
            publishStatus(ERROR, asynchResult.getFailCause());
        }
    }

    private Context context;
    private ManagerStatus currentStatus;
}